<?php

namespace App\Http\Controllers;

use App\Models\Sell;
use App\Models\Seller;
use App\Models\User;
use Illuminate\Http\Request;

class SubSellerController extends Controller
{
  public function index()
  {
    $page = auth()->user()->subs()
      ->select('id', 'username', 'mobile', 'created_at', 'perms')
      ->latest()
      ->page();

    return success($page);
  }

  public function perms(Request $request, $id)
  {
    $sub = User::findOrFail($id);
    $perms = array_values(array_unique(array_merge($sub->perms ?? [], $request->perms)));
    $sub->perms = $perms;
    $sub->save();
    return success('ok');
  }

  public function add(Request $request)
  {
    $exists = User::where('username', $request->username)->exists();
    if ($exists) {
      fail('用户名已注册');
    }
    $user = User::create([
      'pid' => auth()->id(),
      'username' => $request->username,
      'password' => bcrypt($request->password),
      'role' => 'seller',
      'mobile' => $request->mobile,
      'perms' => ['password', 'security']
    ]);

    return success($user);
  }

  public function destroy($id)
  {
    User::destroy($id);
    return success('ok');
  }

  public function update($id, Request $request)
  {
    $input = $request->only(['username', 'mobile']);
    if ($request->filled('password')) {
      $input['password'] = bcrypt($request->password);
    }

    $user = User::findOrFail($id);
    $user->update($input);
    return success('ok');
  }
}
